<?php
/**
 * @Descripttion:
 * @author Siebe
 * @date 2022-02-17 2:33
 */

namespace app\admin\exception;

use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    //需要返回客户端当前请求的URL路径

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException){
            //如果是自定义的异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            if(env('APP_DEBUG', '0')){
                return parent::render($request, $e);
            }else {
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->errorCode = 10000;
                $this->recordErrorLog($e);
            }
        }
        $result = [
            'error_code' => $this->errorCode,
            'msg'  => $this->msg,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }
    //记录日志
    private function recordErrorLog(Exception $e){
        Log::record($e->getMessage(),'error');
    }
}